# appConfig
import os
from pathlib import Path

import yaml
from pydantic import BaseModel, Field


class Project(BaseModel):
    name: str


class Server(BaseModel):
    ip: str | None
    port: int


class Log(BaseModel):
    level: str
    path: str
    keep_days: int = Field(..., alias="keep-days")


# 数据库配置类
class Db(BaseModel):
    host: str
    port: int
    user: str
    password: str
    db_name: str = Field(..., alias="db-name")
    pool_size: int = Field(..., alias="pool-size")


# nacos配置类
class NacosConfig(BaseModel):
    enable: bool
    addr: str
    username: str
    password: str
    namespace: str
    group: str


# 总配置类
class AppConfig(BaseModel):
    project: Project
    server: Server
    log: Log
    db: Db
    nacos: NacosConfig


# 初始化配置
def init_config() -> AppConfig:
    # 外挂文件存在则优先读取外挂文件
    external_config_path = "/app/config.yaml"
    if os.path.exists(external_config_path):
        try:
            with open(external_config_path, encoding="utf-8") as f:
                data = yaml.safe_load(f)
                return AppConfig(**data)
        except Exception as e:
            raise RuntimeError(f"加载外部配置文件失败: {e}")

    current_file_path = Path(__file__).resolve()
    root_dir = current_file_path.parent.parent
    inner_config_path = root_dir / "config" / "config.yaml"

    if not inner_config_path.exists():
        raise FileNotFoundError(f"内部配置文件不存在: {inner_config_path}")

    try:
        with open(inner_config_path, encoding="utf-8") as f:
            data = yaml.safe_load(f)
            return AppConfig(**data)
    except Exception as e:
        raise RuntimeError(f"加载内部配置文件失败: {e}")


# 初始化
app_config = init_config()
